package org.yxj.lib_downfile.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.google.gson.Gson;
import org.yxj.lib_downfile.LogUtil;
import org.yxj.lib_downfile.bean.DownFileBean;
import org.yxj.lib_downfile.db.AppSQLiteHelper;
import org.yxj.lib_downfile.m.AppSQLiteManager;
import org.yxj.lib_downfile.db.DownFileTable;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author on 2022/8/25
 */
public class DownFileDao {


    private AppSQLiteHelper helper;
    private SQLiteDatabase db;
    private Context context ;


    public DownFileDao(Context context) {
        this.context=context;
        helper = AppSQLiteManager.getInstance().getHelper();
        db = helper.getWritableDatabase();
    }


    /**
     * 插入数据
     *
     * @param downFileBean
     */
    public void insert(DownFileBean downFileBean) {
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getWritableDatabase();
        }
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(DownFileTable.fileName, downFileBean.fileName);
        values.put(DownFileTable.filePath, downFileBean.filePath);
        values.put(DownFileTable.fileUrl, downFileBean.fileUrl);
        values.put(DownFileTable.fileTotalLength, downFileBean.fileTotalLength);
        values.put(DownFileTable.currentProgress, downFileBean.currentProgress);
        long val = db.insert(DownFileTable.table, null, values);
        db.setTransactionSuccessful();
        db.endTransaction();
        LogUtil.LOG_V("[DownFileBean]->val = " + val);
    }


    /**
     * 查询数据
     *
     * @return
     */
    @SuppressLint("Range")
    public List<DownFileBean> queryData() {
        List<DownFileBean> list = new ArrayList<>();
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getReadableDatabase();
        }
        db.beginTransaction();
        Cursor cursor = db.query(DownFileTable.table, null, null, null, null, null, null);
        if (cursor != null) {
            int count = cursor.getCount();
            if (count > 0) {
                while (cursor.moveToNext()) {
                    DownFileBean downFileBean = new DownFileBean();
                    downFileBean.fileName = cursor.getString(cursor.getColumnIndex(DownFileTable.fileName));
                    downFileBean.filePath = cursor.getString(cursor.getColumnIndex(DownFileTable.filePath));
                    downFileBean.fileUrl = cursor.getString(cursor.getColumnIndex(DownFileTable.fileUrl));
                    downFileBean.currentProgress = cursor.getInt(cursor.getColumnIndex(DownFileTable.currentProgress));
                    downFileBean.fileTotalLength = cursor.getInt(cursor.getColumnIndex(DownFileTable.fileTotalLength));
                    list.add(downFileBean);
                }
                cursor.close();
            }
        }
        db.setTransactionSuccessful();
        db.endTransaction();



        if (list.size()>0){
            Iterator<DownFileBean> it = list.iterator();
            while (it.hasNext()){
                DownFileBean downFileBean = it.next();
                if (downFileBean!=null&&!isHaveFile(downFileBean.filePath)){
                    LogUtil.LOG_V("[isHaveFile]->"+isHaveFile(downFileBean.filePath));
                    deleteByFileUrl(downFileBean.fileUrl);
                    it.remove();
                }
            }
        }

        return list;
    }


    /**
     * 根据名字查询
     *
     * @param url
     * @return
     */
    @SuppressLint("Range")
    public DownFileBean queryByFileUrl(String url) {
        DownFileBean downFileBean = null;
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getReadableDatabase();
        }
        db.beginTransaction();

        Cursor cursor = db.query(DownFileTable.table, null, DownFileTable.fileUrl + "= '" + url + "'", null, null, null, null);
        if (cursor != null) {
            int count = cursor.getCount();
            if (count > 0) {
                while (cursor.moveToNext()) {
                    downFileBean = new DownFileBean();
                    downFileBean.fileName = cursor.getString(cursor.getColumnIndex(DownFileTable.fileName));
                    downFileBean.filePath = cursor.getString(cursor.getColumnIndex(DownFileTable.filePath));
                    downFileBean.currentProgress = cursor.getInt(cursor.getColumnIndex(DownFileTable.currentProgress));
                    downFileBean.fileTotalLength = cursor.getInt(cursor.getColumnIndex(DownFileTable.fileTotalLength));
                    downFileBean.fileUrl = cursor.getString(cursor.getColumnIndex(DownFileTable.fileUrl));
                }
                cursor.close();
            }
        }
        db.setTransactionSuccessful();
        db.endTransaction();


        if (downFileBean!=null&&!isHaveFile(downFileBean.filePath)){
            LogUtil.LOG_V("[isHaveFile]->"+isHaveFile(downFileBean.filePath));
            deleteByFileUrl(downFileBean.fileUrl);
            downFileBean = null ;
        }

        return downFileBean;
    }


    /**
     * 文件是否存在
     *
     * @return
     */
    public boolean isHaveFile(String path) {
        File file = new File(path);
        return file != null && file.exists() && file.isFile();
    }



    /**
     * 数据能查询到
     *
     * @return
     */
    public boolean isHave(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return queryByFileUrl(url) != null;
    }


    /**
     * 修改数据
     *
     * @param downFileBean
     */
    public void update(DownFileBean downFileBean) {
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getReadableDatabase();
        }
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(DownFileTable.fileName, downFileBean.fileName);
        values.put(DownFileTable.filePath, downFileBean.filePath);
        values.put(DownFileTable.fileUrl, downFileBean.fileUrl);
        values.put(DownFileTable.fileTotalLength, downFileBean.fileTotalLength);
        values.put(DownFileTable.currentProgress, downFileBean.currentProgress);
        db.update(DownFileTable.table, values, DownFileTable.fileUrl + "='" + downFileBean.fileUrl + "'", null);
        db.setTransactionSuccessful();
        db.endTransaction();
        LogUtil.LOG_V("[]->update = " + new Gson().toJson(downFileBean));
    }


    /**
     * 删除通过下载文件链接
     *
     * @param url
     */
    public void deleteByFileUrl(String url) {
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getReadableDatabase();
        }
        db.beginTransaction();
        int code = db.delete(DownFileTable.table, DownFileTable.fileUrl + "=?", new String[]{url});
        db.setTransactionSuccessful();
        db.endTransaction();
        LogUtil.LOG_V("[]->deleteByFileUrl=" + code);
    }


    /**
     * 清空当前表
     */
    public void clear() {
        if (!db.isOpen()) {
            helper = new AppSQLiteHelper(context);
            db = helper.getReadableDatabase();
        }
        db.beginTransaction();
        db.execSQL("delete from " + DownFileTable.table);
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}
